<?php 

namespace pmvc\mvc\security\basic;

use pmvc\util\ClassUtil;
use pmvc\mvc\security\Authenticator;
use pmvc\mvc\security\Authentication;
use pmvc\mvc\security\PasswordEncoder;
use \Exception;

class BasicAuthenticator
	implements Authenticator {

	private $passwordEncoder;
	private $userDao;

	public function authenticate(Authentication $authentication) {

		// check auth type
		if (!ClassUtil::isInstance($authentication, 'pmvc\mvc\security\basic\BasicAuthentication')) {
			throw new Exception("BasicAuthenticator requires BasicAuthentication types");
		}

		// get user
		$user = $this->userDao->getUser($authentication);

		// user not found
		if ($user==NULL) {
			return NULL;

		// make sure it's the right type
		} else if (!ClassUtil::isInstance($user, 'pmvc\mvc\security\basic\BasicUser')) {
			throw new Exception(
				'BasicAuthenticator requires Users that '
				. 'inherit from type pmvc\mvc\security\basic\BasicUser');
		}

		// encode the password if needed
		$userPassword = $authentication->getPassword();
		if ($this->passwordEncoder!=NULL && $user->isPasswordEncoded()) {
			$userPassword = $this->passwordEncoder->encode($userPassword);
		}

		// compare passwords
		return ($userPassword==$user->getPassword()) ? $user : NULL;
	}

	public function supports(Authentication $authentication) {
		return ClassUtil::isInstance(
			$authentication, 'pmvc\mvc\security\basic\BasicAuthentication');
	}

	public function setUserDao(UserDao $userDao) {
		$this->userDao = $userDao;
	}

	public function setPasswordEncoder(PasswordEncoder $passwordEncoder) {
		$this->passwordEncoder = $passwordEncoder;
	}

}

?>